package com.power.structure.linked;

/**
 * @description:
 * @author: jiangnan
 * @time: 2021/6/11 3:41 下午
 */
public class DoubleCycleLinkedList {

    Node head;
    Node tail;
    private int size;

    class Node {
        Node pre;
        Node next;
        int value;

        public Node(int value) {
            this.value = value;
        }
    }


    public void add(int value) {
        Node node = new Node(value);
        if (size == 0) {
            tail = head = node;
        } else if (size == 1) {
            head.next = node;
            node.pre = head;
            head.pre = node;
            node.next = head;
        } else {

            node.pre = head.pre;
            node.next = head;
            head.pre.next = node;
            head.pre = node;
            //尾部插入数据
            node.next = head;
            node.pre = head.pre;
            head.pre = node;

        }
        size++;
    }

    public void remove(int element) {
        int count = 0;
        //从头开始遍历
        Node tmp = head;
        //
        while (tmp != null && count < size) {
            //如果值相等  删除节点
            if (tmp.value == element) {
                tmp.next.pre = tmp.pre;
                tmp.pre.next = tmp.next;
                size--;
            }
            tmp = tmp.next;
            count++;
        }
    }

    public int size() {
        return size;
    }

    public void display(Node node) {
        Node tmp = node;
        int count = 0;
        while (tmp != null) {
            if (count == size) {
                break;
            }
            System.out.println(tmp.value);
            count++;
            tmp = tmp.next;
        }
        System.out.println("\n");
    }

    public static void main(String[] args) {
        DoubleCycleLinkedList doubleCycleLinkedList = new DoubleCycleLinkedList();
        for (int i = 0; i < 10; i++) {
            doubleCycleLinkedList.add(i);
        }
        doubleCycleLinkedList.display(doubleCycleLinkedList.head);
        doubleCycleLinkedList.remove(3);
        doubleCycleLinkedList.display(doubleCycleLinkedList.head);
    }
}
